var hprose = require('./hprose.js');
var rootDocment = 'https://otoapi.zmmedical.cn/api/';
var rpcUrl = "http://service.zmmedical.cn/"; 
var header = {
  'content-type': 'application/json',
  'authentication': wx.getStorageSync('keys') ? wx.getStorageSync('keys') : ''
}
function getReq(url, fun) {
  wx.showLoading({
    title: '加载中',
  })
  // console.log("header==", header)
  wx.request({
    url: rootDocment + url,
    method: 'get',
    header: header,
    success: function (res) {
      wx.hideLoading();
      return typeof fun == "function" && fun(res.data)
    },
    fail: function () {
      wx.hideLoading();
      wx.showModal({
        title: '网络错误',
        content: '网络出错，请刷新重试',
        showCancel: false
      })
      return typeof fun == "function" && fun(false)
    }
  })
}

function postReq(url, data, fun) {
  wx.showLoading({
    title: '加载中',
  })
  // console.log("header=="),
    // console.log(header),
    wx.request({
      url: rootDocment + url,
      header: header,
      data: data,
      method: 'post',
      success: function (res) {
        wx.hideLoading();
        return typeof fun == "function" && fun(res.data)
      },
      fail: function () {
        wx.hideLoading();
        wx.showModal({
          title: '网络错误',
          content: '网络出错，请刷新重试',
          showCancel: false
        })
        return typeof fun == "function" && fun(false)
      }
    })
}

function noLoadReq(url, data, method,fun) {  
  wx.request({
    url: rootDocment + url,
    header: header,
    data: data,
    method: method,
    success: function (res) {
      wx.hideLoading();
      return typeof fun == "function" && fun(res.data)
    },
    fail: function () {
      wx.showModal({
        title: '网络错误',
        content: '网络出错，请刷新重试',
        showCancel: false
      })
      return typeof fun == "function" && fun(false)
    }
  })
}

function signid(array) {
  rpctokenid();
  var tokenId = wx.getStorageSync('tokenId');
  if (!tokenId) {
    var client = hprose.Client.create(rpcUrl+"user/user", ["getAccessToken"]);
    client.getAccessToken("web.tc", '123465', function (result) {
      var res = JSON.parse(result)
      tokenId = res.data.token
    });
  }
  var client = hprose.Client.create(rpcUrl+"user/user", ["createSign"]);
  client.createSign(array, tokenId, function (result) {
    var signRes = JSON.parse(result);
    wx.setStorageSync('signid', res.data.sign);
  });
}
function rpctokenid() {
  var client = hprose.Client.create(rpcUrl+"user/user", ["getAccessToken"]);
  client.getAccessToken("web.tc", '123465', function (result) {
    var res = JSON.parse(result)
    wx.setStorageSync('tokenId', res.data.token);
  });
}

module.exports = {
  getReq: getReq,
  postReq: postReq,
  noLoadReq: noLoadReq,
  header: header,
  hprose: hprose,
  rpcUrl: rpcUrl,
  signid: signid
}